package com.ynkbny.util;

import com.ynkbny.aspect.TaskOperationLog;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @author zelin.wang
 * @description 扫描指定包下的所有类
 * @date 8/22/2023
 */
public class ClassUtil {
    public static Map<String,String> loadClass(String packageName, Class clz) {
        /**
         * spring工具类,获取指定路径下全部类
         */
        final String BASE_PACKAGE = packageName;
        final String RESOURCE_PATTERN = "/**/*.class";
        Map<String,String> map = new HashMap<>();
        if (packageName == null || clz == null) {
            return map;
        }
        //spring工具类，可以获取指定路径下的全部类
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            //MetadataReader 的工厂类
            MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                //用于读取类信息
                MetadataReader reader = readerfactory.getMetadataReader((org.springframework.core.io.Resource) resource);
                //扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);
                if (clz.isAssignableFrom(clazz)) {
//                    list.add(clazz.getName());
                    map.put(clazz.getName(),clazz.getMethod("execute",org.quartz.JobExecutionContext.class).getAnnotation(TaskOperationLog.class).description());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
